package com.njym.java.security.admin.rest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njym.java.security.admin.biz.FamilyUserBiz;
import com.njym.java.security.admin.biz.MenuBiz;
import com.njym.java.security.admin.biz.UserBiz;
import com.njym.java.security.admin.entity.FamilyUser;
import com.njym.java.security.admin.entity.Menu;
import com.njym.java.security.admin.entity.User;
import com.njym.java.security.admin.entity.UserVo;
import com.njym.java.security.admin.rpc.service.PermissionService;
import com.njym.java.security.admin.vo.CatVo;
import com.njym.java.security.admin.vo.FrontUser;
import com.njym.java.security.admin.vo.MenuTree;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.msg.TableResultResponse;
import com.njym.java.security.common.notify.NotifyService;
import com.njym.java.security.common.notify.NotifyType;
import com.njym.java.security.common.rest.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.concurrent.*;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 11:51
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController<UserBiz,User> {
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private MenuBiz menuBiz;
    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserBiz userBiz;

    @Autowired
    private FamilyUserBiz familyUserBiz;

    /**
     * 池中所保存的线程数，包括空闲线程。
     */
    private final static int CORE_POOL_SIZE = 7;

    /**
     * 池中允许的最大线程数。
     */
    private final static int MAXIMUM_POOL_SIZE = 10;

    /**
     * 当线程数大于核心线程时，此为终止前多余的空闲线程等待新任务的最长时间1s
     */
    private final static long KEEP_ALIVE_TIME = 1000;

    /**
     * 执行前用于保持任务的队列，即任务缓存队列
     */
    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(2048);

    /**
     * 拒绝策略，都满的情况下把被拒绝的线程重新执行
     */
    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);

    @RequestMapping(value = "/front/info", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getUserInfo(String token) throws Exception {
        FrontUser userInfo = permissionService.getUserInfo(token);
        if(userInfo==null) {
            return ResponseEntity.status(401).body(false);
        } else {
            return ResponseEntity.ok(userInfo);
        }
    }

    @RequestMapping(value = "/front/menus", method = RequestMethod.GET)
    public @ResponseBody
    List<MenuTree> getMenusByUsername(String token) throws Exception {
        return permissionService.getMenusByUsername(token);
    }

    @RequestMapping(value = "/front/menu/all", method = RequestMethod.GET)
    public @ResponseBody
    List<Menu> getAllMenus() throws Exception {
        return menuBiz.selectListAll();
    }

    /**
     * 总部查询，查手下所有圈主的用户任务完成度
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cicleMasterList", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<UserVo> cicleMasterList(@RequestParam(defaultValue = "1") int page,
                                                      @RequestParam(defaultValue = "20") int limit,
                                      String name) throws Exception {
        PageHelper.startPage(page,limit);
        List<UserVo> rows = userBiz.cicleMasterList(name);
        int total = userBiz.countMasterList(name);
        Map<String, Object> data = new HashMap<>(2);
        data.put("rows", rows);
        data.put("total", total);
        return new ObjectRestResponse<UserVo>().rel(true).data(data);
    }

    /**
     * 圈主查询，查手下所有圈友的用户任务完成度
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cicleFriendList", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<UserVo> cicleFriendList(@RequestParam(defaultValue = "1") int page,
                                                      @RequestParam(defaultValue = "20") int limit,
                                                      String name, Integer pid) throws Exception {
        PageHelper.startPage(page,limit);
        List<UserVo> rows = userBiz.cicleFriendList(name, pid);
        int total = userBiz.countFriendList(name, pid);
        Map<String, Object> data = new HashMap<>(2);
        data.put("rows", rows);
        data.put("total", total);
        return new ObjectRestResponse<UserVo>().rel(true).data(data);
    }

    /**
     * 圈圈友查询，查手下所有指导师的用户任务完成度
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/teacherList", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<UserVo> teacherList(@RequestParam(defaultValue = "1") int page,
                                                      @RequestParam(defaultValue = "20") int limit,
                                                      String name, Integer pid) throws Exception {
        PageHelper.startPage(page,limit);
        List<UserVo> rows = userBiz.teacherList(name, pid);
        int total = userBiz.countTeacherList(name, pid);
        Map<String, Object> data = new HashMap<>(2);
        data.put("rows", rows);
        data.put("total", total);
        return new ObjectRestResponse<UserVo>().rel(true).data(data);
    }

//    @RequestMapping(value = "/changefamilyuser",method = RequestMethod.GET)
//    @ResponseBody
//    public Object changeFamilyUser() {
//        Example example = new Example(FamilyUser.class);
//        example.createCriteria().andEqualTo("")
//        return null;
//    }

    @RequestMapping(value = "/updateGeneralize",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<User> updateGeneralize(Integer id, String status, String code, String mobile) {

        baseBiz.updateDaiLi(status, id);

        Example example = new Example(FamilyUser.class);
        example.createCriteria().andEqualTo("mobile", mobile);
        List<FamilyUser> list = familyUserBiz.selectByExample(example);

        if(list.size() > 0) {
            FamilyUser user = list.get(0);
            if ("1".equals(status)) {
                user.setTeacherId(id);
                user.setBaseId(code);
                user.setFuserId(code);
                familyUserBiz.updateById(user);
            }
        }

        Map<String, Object> data = new HashMap<>(2);

        return new ObjectRestResponse<User>().rel(true).data(data);
    }

    /**
     * 判断推广码是否重复
     * @param code
     * @return
     */
    @RequestMapping(value = "/queryByCode",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<User> queryByCode(String code) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("attr4", code);
        List<User> user = baseBiz.selectByExample(example);


        Map<String, Object> data = new HashMap<>(2);
        data.put("num", user.size());
        return new ObjectRestResponse<User>().rel(true).data(data);
    }


    @RequestMapping(value = "/queryuserlevel",method = RequestMethod.GET)
    @ResponseBody
    public Object queryUserLevel() {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("identity", 1);
        List<User> user = baseBiz.selectByExample(example);

        return user;
    }

    public String genRandomNum(){
        int  maxNum = 36;
        int i;
        int count = 0;
        char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < 5){
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return pwd.toString();
    }
    @RequestMapping(value = "/sendMessage",method = RequestMethod.GET)
    @ResponseBody
    public Object sendMessage() {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("identity", "1").andEqualTo("attr5", "1");
        List<User> user = userBiz.selectByExample(example);

        for (int i = 0; i < user.size(); i++){
            if(user.get(i).getMobilePhone() != null && user.get(i).getMobilePhone().length() == 11) {
               String  mobile =  user.get(i).getMobilePhone();
                String params = new String("{}");
                //发送短信
                //发送推广人信息
                Callable<Object> sendMessage = () -> notifyService.notifySmsTemplateSync(mobile, NotifyType.TISHI, params);
                FutureTask<Object> sends = new FutureTask<>(sendMessage);
                executorService.submit(sends);
            }
        }
        return null;
    }
}
